<?php


class RealtyController extends Zend_Controller_Action 
{
    function init()
    {
        $this->initView();
        Zend_Loader::loadClass('AuxDbTable');
        Zend_Loader::loadClass('User');
        Zend_Loader::loadClass('Realty');
        Zend_Loader::loadClass('Mainmenu');
        Zend_Loader::loadClass('City');
        Zend_Loader::loadClass('Type');
        Zend_Loader::loadClass('Renovation');
        
        $this->view->baseUrl = $this->_request->getBaseUrl();
        $this->view->user = Zend_Auth::getInstance()->getIdentity();
    }
    
    function preDispatch()
    {
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity()) {
            $this->_redirect('auth/login');
        }
        $menu = new Mainmenu();
        $this->view->main_menu = $menu->getMenu($this->view->user->id);
        $city = new City();
        $this->view->citys = $city->getAll();
        $type = new Type();
        $this->view->types = $type->getAll();
        $ren = new Renovation();
        $this->view->renovations = $ren->getAll();
    }

    function indexAction()
    {
        $this->view->title = $this->view->content_title = "Недвижимость";
        $realty = new Realty();
        
        $this->view->item = new stdClass();
        
        $this->view->item->from_date = $this->_request->getParam('from_date', 0)?$this->_request->getParam('from_date', 0):date('Y-m-01');
        $this->view->item->to_date = $this->_request->getParam('to_date', 0)?$this->_request->getParam('to_date', 0):date('Y-m-t');
        $this->view->item->city = $this->_request->getParam('city', 0)?$this->_request->getParam('city', 0):0;
        $this->view->item->street = $this->_request->getParam('street', 0)?$this->_request->getParam('street', 0):'';
        $this->view->item->flats = $this->_request->getParam('flats', 0)?$this->_request->getParam('flats', 0):'';
        $this->view->item->type = $this->_request->getParam('type', 0)?$this->_request->getParam('type', 0):0;
        
        $cond = array('deleted!=1');
        foreach($this->view->item as $key=>$value) {
            if($value) {
                switch($key) {
                    case 'from_date':
                        $cond[] = 'today >= "'.$value.'"';
                        break;
                    case 'to_date':
                        $cond[] = 'today <= "'.$value.'"';
                        break;
                    default :
                        $cond[] = $key.'="'.$value.'"';
                        break;
                }
                $this->view->path .= '/'.$key.'/'.$value;
            }
        }
        
        
        $this->view->items = $realty->fetchAll($cond);
        
        $this->view->can_add = true;
        $this->view->can_edit = true;
        $this->view->can_delete = true;
        
        $this->render();
    }
    
    function validate($id,$params)
    {
        $valid = true;
        $obj = new Realty();
        
        if(strlen($params['today'])==0)
        {
            $this->view->message .= 'Пожалуйста введите дату ввода данных.<br>';
            $valid = false;
        }    
        if(strlen($params['street'])==0)
        {
            $this->view->message .= 'Пожалуйста введите микрорайон или улицу.<br>';
            $valid = false;
        }    
        if(strlen($params['house'])==0)
        {
            $this->view->message .= 'Пожалуйста введите номер дома.<br>';
            $valid = false;
        }    
        if(strlen($params['flats'])==0)
        {
            $this->view->message .= 'Пожалуйста введите количество комнат.<br>';
            $valid = false;
        }    
        if(strlen($params['floors'])==0)
        {
            $this->view->message .= 'Пожалуйста введите этажность лома.<br>';
            $valid = false;
        }    
        if(strlen($params['floor'])==0)
        {
            $this->view->message .= 'Пожалуйста введите этаж.<br>';
            $valid = false;
        }    
        if(strlen($params['square'])==0)
        {
            $this->view->message .= 'Пожалуйста введите общую площадь.<br>';
            $valid = false;
        }    
        if(strlen($params['price'])==0)
        {
            $this->view->message .= 'Пожалуйста введите цену.<br>';
            $valid = false;
        }    
                if(!$params['flats'])
        {
            $this->view->message .= 'Количество комнат должно быть больше 0.<br>';
            $valid = false;
        }
                if(!$params['floors'])
        {
            $this->view->message .= 'Этажность должна быть больше 0.<br>';
            $valid = false;
        }
                if(!$params['floor'])
        {
            $this->view->message .= 'Этаж должен быть больше 0.<br>';
            $valid = false;
        }
                if(!$params['square'])
        {
            $this->view->message .= 'Общая площадь должна быть больше 0.<br>';
            $valid = false;
        }
                
        
        //date 
        $date_pattern = '/^[0-9]{4}\-(?:0[1-9]|1[0-2])\-(?:[0-2]?[0-9]|3[0-1])$/';
        if(!preg_match($date_pattern,$params['today']))
        {
            $this->view->message .= 'Неправильная дата '.$params['today'].'. Формат гггг-мм-дд.<br>';
            $valid = false;
        } 
                
        return $valid;
    }
    function addAction()
    {
        $this->view->content_title = $this->view->title = "Add New Realty";
        $params = array();

        if (strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
            Zend_Loader::loadClass('Zend_Filter_StripTags');
            $filter = new Zend_Filter_StripTags();
            
            $params['today'] = trim($filter->filter($this->_request->getPost('today')));
            $params['city'] = trim($filter->filter($this->_request->getPost('city')));
            $params['street'] = trim($filter->filter($this->_request->getPost('street')));
            $params['region'] = trim($filter->filter($this->_request->getPost('region')));
            $params['house'] = trim($filter->filter($this->_request->getPost('house')));
            $params['flats'] = (int)trim($filter->filter($this->_request->getPost('flats')));
            $params['type'] = trim($filter->filter($this->_request->getPost('type')));
            $params['walls'] = trim($filter->filter($this->_request->getPost('walls')));
            $params['floors'] = (int)trim($filter->filter($this->_request->getPost('floors')));
            $params['floor'] = (int)trim($filter->filter($this->_request->getPost('floor')));
            $params['square'] = (float)trim($filter->filter($this->_request->getPost('square')));
            $params['renovation'] = trim($filter->filter($this->_request->getPost('renovation')));
            $params['price'] = (float)trim($filter->filter($this->_request->getPost('price')));
            $params['source'] = trim($filter->filter($this->_request->getPost('source')));
            $params['description'] = trim($filter->filter($this->_request->getPost('description')));
                    
            $this->view->message = '';
            if($this->validate(0,$params)) {
                $obj = new Realty();
                $new_id = $obj->insert($params);
                
                $this->_redirect('/realty');
                return;
            }
        } 
        
        // set up an "empty" realty        
        $this->view->item = new stdClass();
        $this->view->item->id = null;
        $this->view->item->today = isset($params['today'])?$params['today']:date('Y-m-d');
        $this->view->item->city = isset($params['city'])?$params['city']:'';
        $this->view->item->street = isset($params['street'])?$params['street']:'';
        $this->view->item->region = isset($params['region'])?$params['region']:'';
        $this->view->item->house = isset($params['house'])?$params['house']:'';
        $this->view->item->flats = isset($params['flats'])?$params['flats']:'';
        $this->view->item->type = isset($params['type'])?$params['type']:'';
        $this->view->item->walls = isset($params['walls'])?$params['walls']:'';
        $this->view->item->floors = isset($params['floors'])?$params['floors']:'';
        $this->view->item->floor = isset($params['floor'])?$params['floor']:'';
        $this->view->item->square = isset($params['square'])?$params['square']:'';
        $this->view->item->renovation = isset($params['renovation'])?$params['renovation']:'';
        $this->view->item->price = isset($params['price'])?$params['price']:'';
        $this->view->item->source = isset($params['source'])?$params['source']:'';
        $this->view->item->description = isset($params['description'])?$params['description']:'';
                        
                    
        // additional view fields required by form
        $this->view->action = 'add';
        $this->render();
    }
    
    function editAction()
    {
        $this->view->content_title = $this->view->title = "Edit Realty";
        $obj = new Realty();
        
        if (strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
            Zend_Loader::loadClass('Zend_Filter_StripTags');
            $filter = new Zend_Filter_StripTags();
            
            $id = (int)$this->_request->getPost('id');
            $params = array();
            $params['today'] = trim($filter->filter($this->_request->getPost('today')));
            $params['city'] = trim($filter->filter($this->_request->getPost('city')));
            $params['street'] = trim($filter->filter($this->_request->getPost('street')));
            $params['region'] = trim($filter->filter($this->_request->getPost('region')));
            $params['house'] = trim($filter->filter($this->_request->getPost('house')));
            $params['flats'] = (int)trim($filter->filter($this->_request->getPost('flats')));
            $params['type'] = trim($filter->filter($this->_request->getPost('type')));
            $params['walls'] = trim($filter->filter($this->_request->getPost('walls')));
            $params['floors'] = (int)trim($filter->filter($this->_request->getPost('floors')));
            $params['floor'] = (int)trim($filter->filter($this->_request->getPost('floor')));
            $params['square'] = (float)trim($filter->filter($this->_request->getPost('square')));
            $params['renovation'] = trim($filter->filter($this->_request->getPost('renovation')));
            $params['price'] = (float)trim($filter->filter($this->_request->getPost('price')));
            $params['source'] = trim($filter->filter($this->_request->getPost('source')));
            $params['description'] = trim($filter->filter($this->_request->getPost('description')));
                        
            if ($id !== false) {
                $this->view->message = '';
                if($this->validate($id,$params)) {
                    $where = 'id = ' . $id;
                    $obj->update($params, $where);
                
                    $this->_redirect('/realty');
                    return;
                } else {
                    $this->view->item = $obj->fetchRow('id='.$id);
                    $this->view->item->id = $id;
                    
                    if( $params['today']) $this->view->item->today = $params['today'];
                    if( $params['city']) $this->view->item->city = $params['city'];
                    if( $params['street']) $this->view->item->street = $params['street'];
                    if( $params['region']) $this->view->item->region = $params['region'];
                    if( $params['house']) $this->view->item->house = $params['house'];
                    if( $params['flats']) $this->view->item->flats = $params['flats'];
                    if( $params['type']) $this->view->item->type = $params['type'];
                    if( $params['walls']) $this->view->item->walls = $params['walls'];
                    if( $params['floors']) $this->view->item->floors = $params['floors'];
                    if( $params['floor']) $this->view->item->floor = $params['floor'];
                    if( $params['square']) $this->view->item->square = $params['square'];
                    if( $params['renovation']) $this->view->item->renovation = $params['renovation'];
                    if( $params['price']) $this->view->item->price = $params['price'];
                    if( $params['source']) $this->view->item->source = $params['source'];
                    if( $params['description']) $this->view->item->description = $params['description'];
                                    
                }
            }
        } else {
            $id = (int)$this->_request->getParam('id', 0);
            if ($id > 0) {
                $this->view->item = $obj->fetchRow('id='.$id);
            }
        }

        // additional view fields required by form
        $this->view->action = 'edit';
        
        $this->render();
    }
    
    function deleteAction()
    {
        $this->view->content_title = $this->view->title = "Delete Realty";
        
        $obj = new Realty();
        if (strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
            Zend_Loader::loadClass('Zend_Filter_Alpha');
            $filter = new Zend_Filter_Alpha();
            
            $id = (int)$this->_request->getPost('id');
            $del = $filter->filter($this->_request->getPost('del'));
            
            if ($del == 'Yes' && $id > 0) {
                $data = array(
                        'deleted' => '1'
                );
                $where = 'id = ' . $id;
                $obj->update($data, $where);
            }
        } else {
            $id = (int)$this->_request->getParam('id');
            if ($id > 0) {
                // only render if we have an id and can find the realty.
                $this->view->item = $obj->fetchRow('id='.$id);
                
                if ($this->view->item->id > 0) {
                    $this->render();
                    return;
                }
            }
        }
        
        // redirect back to the project list unless we have rendered the view
        $this->_redirect('/realty');
    }
    
    function excelAction()
    {
        $this->view->title = $this->view->content_title = "Недвижимость";
        $realty = new Realty();
        
        $this->view->item = new stdClass();
        
        $this->view->item->from_date = $this->_request->getParam('from_date', 0)?$this->_request->getParam('from_date', 0):date('Y-m-01');
        $this->view->item->to_date = $this->_request->getParam('to_date', 0)?$this->_request->getParam('to_date', 0):date('Y-m-t');
        $this->view->item->city = $this->_request->getParam('city', 0)?$this->_request->getParam('city', 0):0;
        $this->view->item->street = $this->_request->getParam('street', 0)?$this->_request->getParam('street', 0):'';
        $this->view->item->flats = $this->_request->getParam('flats', 0)?$this->_request->getParam('flats', 0):'';
        $this->view->item->type = $this->_request->getParam('type', 0)?$this->_request->getParam('type', 0):0;
        
        $html = '';
        $cond = array('deleted!=1');
        foreach($this->view->item as $key=>$value) {
            if($value) {
                switch($key) {
                    case 'from_date':
                        $cond[] = 'today >= "'.$value.'"';
                        $html .= 'C '.$value.'<br>';
                        break;
                    case 'to_date':
                        $cond[] = 'today <= "'.$value.'"';
                        $html .= 'По '.$value.'<br>';
                        break;
                    default :
                        $cond[] = $key.'="'.$value.'"';
                        switch($key) {
                            case 'city' :
                                $html .= 'Город : '.$this->view->citys[$value].'<br>';
                                break;
                            case 'street' :
                                $html .= 'Мкр/Улица : '.$value.'<br>';
                                break;
                            case 'flats' :
                                $html .= 'Комнат : '.$value.'<br>';
                                break;
                            case 'Type' :
                                $html .= 'Тип дома : '.$this->view->types[$value].'<br>';
                                break;
                        }
                        break;
                }
            }
        }
        
        $this->view->items = $realty->fetchAll($cond);
        
        $fileName = 'Realty_'.date('Y-m-d').'.xls';

        header('Content-type: application/ms-excel');
        header("Content-Disposition: attachment; filename=".$fileName);
        header("Pragma: no-cache");
        header("Expires: 0");
        
        
        $html .= '
        <table border="1">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Дата</th>
                    <th>Город</th>
                    <th>Мкр/Улица</th>
                    <th>Дом</th>
                    <th>Район</th>
                    <th>Комнат</th>
                    <th>Тип</th>
                    <th>Стены</th>
                    <th>Этаж</th>
                    <th>Этажность</th>
                    <th>Ремонт</th>
                    <th>Площадь кв.м.</th>
                    <th>Цена</th>
                    <th>Источник</th>
                    <th>Описание</th>
                </tr>
            </thead>
            <tbody>';
        foreach($this->view->items as $obj) {
             $html .= '<tr>
                <td>'.$obj->id.'</td>
                <td>'.$obj->today.'</td>
                <td>'.$this->view->citys[$obj->city].'</td>
                <td>'.$obj->street.'</td>
                <td>'.$obj->house.'</td>
                <td>'.$obj->region.'</td>
                <td>'.$obj->flats.'</td>
                <td>'.$this->view->types[$obj->type].'</td>
                <td>'.$obj->walls.'</td>
                <td>'.$obj->floor.'</td>
                <td>'.$obj->floors.'</td>
                <td>'.$this->view->renovations[$obj->renovation].'</td>
                <td>'.$obj->square.'</td>
                <td>'.$obj->price.'</td>
                <td>'.$obj->source.'</td>
                <td>'.$obj->description.'</td>
             </tr>';
        } 
                       
        $html .= '</tbody></table>';
        echo $html;
        exit();
    }
    
}